﻿#include "graphicsitem.h"
#include "graphicsscene.h"
#include <QGraphicsSceneMouseEvent>

GraphicsScene::GraphicsScene(QObject *parent) : QGraphicsScene(parent)
{
    m_pMoveItem = NULL;
}

void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    QPointF mousePos(event->buttonDownScenePos(Qt::LeftButton).x(),
                     event->buttonDownScenePos(Qt::LeftButton).y());
    const QList<QGraphicsItem *> itemList = items(mousePos);
    m_pMoveItem = itemList.isEmpty() ? 0 : itemList.first();

    if (m_pMoveItem != 0 && event->button() == Qt::LeftButton) {
        oldPos = m_pMoveItem->pos();
    }

    clearSelection();
    QGraphicsScene::mousePressEvent(event);
}

void GraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if (m_pMoveItem != 0 && event->button() == Qt::LeftButton) {
        if (oldPos != m_pMoveItem->pos())
            emit itemMoved(qgraphicsitem_cast<GraphicsItem *>(m_pMoveItem),
                           oldPos);
        m_pMoveItem = 0;
    }
    QGraphicsScene::mouseReleaseEvent(event);
}
